<template>
  <div class="maincontain">
    <div class="filter-bar"></div>

    <div class="userlist">
      <div class="newbtn">
        <a-button
          type="primary"
          @click="
            () => {
              AddApply();
            }
          "
          >添加申请</a-button
        >
      </div>
      <a-table
        :pagination="pagination"
        @change="handleTableChange"
        :dataSource="dataSource"
        :columns="columns"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space wrap>
              <a-button
                size="small"
                type="primary"
                @click="
                  () => {
                    showEditModal(record);
                  }
                "
                >修改</a-button
              >
            </a-space>
          </template>
        </template>
      </a-table>

      <a-modal
        v-model:visible="addModalVisible"
        title="添加申请"
        okText="提交"
        cancelText="取消"
        centered="true"
        @ok="confirmAddApply"
        @cancel="closeAddModal"
      >
        <a-form layout="vertical">
          <a-form-item label="实验室类型">
            <a-select
              v-model:value="newApply.labType"
              placeholder="请选择实验室类型"
              style="width: 100%"
              allowClear="true"
            >
              <a-select-option
                v-for="labType in labTypes"
                :key="labType.value"
                :value="labType.value"
              >
                {{ labType.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="课程名">
            <a-input
              v-model:value="newApply.courseName"
              placeholder="请输入课程名"
              required
            />
          </a-form-item>

          <a-form-item label="学生班级">
            <a-input
              v-model:value="newApply.className"
              placeholder="请输入学生班级"
              required
            />
          </a-form-item>
          <a-form-item label="学生人数">
            <a-input
              v-model:value="newApply.studentNum"
              placeholder="请输入学生人数"
              required
            />
          </a-form-item>
          <a-form-item label="开始周">
            <a-input-number
              v-model:value="newApply.beginWeek"
              min="1"
              style="width: 100%"
              placeholder="请输入开始周"
              required
              max="25"
            />
          </a-form-item>
          <a-form-item label="结束周">
            <a-input-number
              v-model:value="newApply.endWeek"
              min="1"
              style="width: 100%"
              placeholder="请输入结束周"
              required
              max="25"
            />
          </a-form-item>
          <a-form-item label="节次">
            <a-input-number
              v-model:value="newApply.amountOfSession"
              min="1"
              style="width: 100%"
              placeholder="请输入节次"
              required
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        v-model:visible="isEditModalVisible"
        title="撤回申请信息"
        @ok="submitEditForm"
        @cancel="closeEditModal"
        okText="确认撤回"
      >
        <div>您确定要撤回该申请吗？</div>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, createVNode, onMounted, ref } from "vue";

import {
  teacherApplyQuery,
  techerApplyUpdate,
  teacherApplyCheck,
} from "@/api/methods/teacherReq";

import { omit } from "lodash";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { getAllLabType } from "@/api/methods/labManageReq";
import { labTypeQuery } from "@/api/methods/labReq";
import { userInfo, userInfoJson } from "@/utils/userInfo";
import { useLocalStorage } from "@vueuse/core";
const semesterId = useLocalStorage<string>("semesterId", "");
const semesterName = useLocalStorage<string>("semesterName", "");
const columns = [
  {
    title: "申请实验室",
    dataIndex: "labName",
    key: "labName",
    customRender: ({ text, record }) => {
      const labType = labTypes.value.find(
        (labTypeOption) => labTypeOption.value === record.labType
      );
      return labType ? labType.label : text;
    },
  },
  { title: "申请学期", dataIndex: "semesterName", key: "semesterName" },
  { title: "课程名称", dataIndex: "courseName", key: "courseName" },
  { title: "学生班级", dataIndex: "className", key: "className" },
  { title: "学生人数", dataIndex: "studentNum", key: "studentNum" },
  { title: "开始周", dataIndex: "beginWeek", key: "beginWeek" },
  { title: "结束周", dataIndex: "endWeek", key: "endWeek" },
  {
    title: "节次",
    dataIndex: "amountOfSession",
    key: "amountOfSession",
    customRender: ({ text, record }) => {
      return translateSession(text);
    },
  },
  {
    title: "申请进度",
    dataIndex: "state",
    key: "state",
    customRender: ({ text, record }) => {
      return translateState(text);
    },
  },
  // { title: "操作", dataIndex: "action", key: "action", width: "160px" },
];

const router = useRouter();
const dataSource = ref();
const pageConfig = ref({
  pageSize: 10,
  page: 1,
  total: 0,
});
interface IPagenation {
  current: number;
  pageSize: number;
  total: number;
}
const pagination = computed(() => ({
  total: pageConfig.value.total,
  current: pageConfig.value.page,
  pageSize: pageConfig.value.pageSize,
}));
const loading = ref(false);
const handleTableChange = async (pagination: IPagenation) => {
  pageConfig.value.page = pagination.current;
  pageConfig.value.pageSize = pagination.pageSize;
  loading.value = true;
  const queryParams = {
    ...omit(pageConfig.value, "total"),
    id: userInfo.value.id,
  };
  const { data: res } = await teacherApplyQuery(queryParams);
  reflectMapDataSource(res);
  loading.value = false;
};
onMounted(async () => {
  loading.value = true;
  const queryParams = {
    ...omit(pageConfig.value, "total"),
    id: userInfo.value.id,
  };
  const { data: res } = await teacherApplyQuery(queryParams);
  reflectMapDataSource(res);
  loading.value = false;
});

const labTypes = ref([]);
onMounted(async () => {
  try {
    const labTypeResult = await labTypeQuery({});
    const labTypeOptions = labTypeResult.data.map((type: any) => ({
      value: type.id,
      label: type.typeName,
    }));
    labTypes.value = labTypeOptions;
  } catch (error) {
    console.error("Error fetching lab types:", error);
  }
});

const reloadData = async () => {
  loading.value = true;
  const queryParams = {
    ...omit(pageConfig.value, "total"),
    id: userInfo.value.id,
  };
  const { data: res } = await teacherApplyQuery(queryParams);
  
  reflectMapDataSource(res);
  loading.value = false;
};

const reflectMapDataSource = (res: any) => {
  pageConfig.value.total = res.total;
  dataSource.value = res.records.map((item: any) => {
    return {
      labName: item.labName,
      labType: item.labType,
      labId: item.labId,
      semesterName: item.semesterName,
      semesterId: item.semesterId,
      courseName: item.courseName,
      className: item.className,
      studentNum: item.studentNum,
      beginWeek: item.beginWeek,
      endWeek: item.endWeek,
      state: item.state,
      amountOfSession: item.amountOfSession,
    };
  });
  console.log(dataSource.value);
};

const isEditModalVisible = ref(false);
const cancelData = ref({
  id: "",
  record: "",
});

const addModalVisible = ref(false);
const newApply = ref({
  teacherId: userInfo.value.id,
  teacherName:userInfo.value.username,
  labType: "",
  labName: "",
  semesterId: semesterId.value,
  semesterName: semesterName.value,
  beginWeek: "",
  endWeek: "",
  studentNum: 0,
  className: "",
  amountOfSession: "",
  courseName: "",
});
function AddApply() {
  addModalVisible.value = true;
}

async function confirmAddApply() {
  try {
    const res=await teacherApplyCheck(newApply.value);
    if(res.data=="暂时没有空余的教室满足课程排课安排！"){
      message.error("暂时没有空余的教室满足课程排课安排！");
    }
    else message.success("添加申请成功");
    closeAddModal();
    await reloadData();
  } catch (error) {
    message.error("没有符合的实验室可安排，请修改申请信息");
  }
}

function closeAddModal() {
  addModalVisible.value = false;
}

const showEditModal = (record: any) => {
  cancelData.value = { ...record };
  isEditModalVisible.value = true;
};

const submitEditForm = async () => {
  try {
    await techerApplyUpdate(cancelData.value);
    message.success("撤回申请成功");
    closeEditModal();
  } catch (error) {
    message.error("撤回申请失败");
  }
};

const closeEditModal = () => {
  isEditModalVisible.value = false;
};

const deleteApply = async (applyId: string) => {
  try {
    const deletedData = {
      id: applyId,
      isDeleted: 1,
    };
    // await editLabApply(deletedData);
    message.success("删除申请成功");
  } catch (error) {
    message.error("删除申请失败");
  }
};

const translateState = (state: number) => {
  switch (state) {
    case 1:
      return "已排课";
    default:
      return "未审核";
  }
};

const translateSession = (session) => {
  switch (session) {
    case 1:
      return "1-2";
    case 2:
      return "3-5";
    case 3:
      return "6-7";
    case 4:
      return "8-9";
    case 5:
      return "10-12";
    case 6:
      return "13-15";
    default:
      return "--";
  }
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
.maincontain {
  display: flex;
  flex-direction: column;
  .createuser {
    margin-bottom: 15px;
  }
  .newbtn {
    margin-bottom: 15px;
  }
}
</style>
